using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using BoxBinary.AspectCache.Core.Helpers;

namespace BoxBinary.AspectCache.Core.ReplicationSink
{
    internal sealed class SinkMonitorThread
    {
        public bool ShouldInterrupt { get; set; }

        internal void Start()
        {
            try
            {
                Trace.WriteLine("In SinkMonitorThread.Start");
                // Maintain the replication sink by deleting stale files
                var dInfo = new DirectoryInfo(SinkManager.GetReplicationSinkRootedPath());

                while (!ShouldInterrupt)
                {
                    Trace.WriteLine("SinkMonitorThread Tick");

                    try
                    {
                        // Purge any files older than 5 minutes
                        int deleteCount = 0;

                        foreach (
                            FileInfo fileInfo in
                                dInfo.GetFiles(string.Format("*{0}", IO.SerializationFileNameExtension),
                                               SearchOption.TopDirectoryOnly))
                        {
                            try
                            {
                                if (fileInfo.Exists && DateTime.Now.Subtract(fileInfo.CreationTime).TotalMinutes > 5)
                                {
                                    if (fileInfo.IsReadOnly) fileInfo.IsReadOnly = false;
                                    File.Delete(fileInfo.FullName);
                                    deleteCount += 1;
                                }
                            }
                            catch (Exception)
                            {
                                SinkWatcher.ConditionalDebug_WriteToTraceLog("Couldn't delete file",
                                                                             fileInfo.Name);
                            }
                        }

                        if (deleteCount > 0)
                        {
                            SinkWatcher.ConditionalDebug_WriteToTraceLog("Housekeeping delete run",
                                                                         string.Format("Deleted {0} files",
                                                                                       deleteCount));
                        }
                    }
                    catch (Exception ex)
                    {
                        Trace.WriteLine(ex.Message);
                    }

                    // Pause check
                    Thread.Sleep(TimeSpan.FromSeconds(30));
                }
            }
            catch (ThreadAbortException)
            {
                // Dispose things nicely here
            }
            catch (Exception genericException)
            {
                SinkWatcher.ConditionalDebug_WriteToTraceLog("Housekeeping thread error",
                                                             genericException.ToString());
            }
        }
    }
}